import aiohttp
import asyncio
from pathlib import Path
from typing import Optional, Callable
from ..core.exceptions import NetworkError

class Downloader:
    def __init__(self, timeout: int = 30, verify_ssl: bool = True):
        self.timeout = timeout
        self.verify_ssl = verify_ssl

    async def download_file(
        self,
        url: str,
        destination: Path,
        progress_callback: Optional[Callable] = None
    ) -> Path:
        """下载文件"""
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(
                    url,
                    timeout=self.timeout,
                    ssl=self.verify_ssl
                ) as response:
                    if response.status != 200:
                        raise NetworkError(
                            f"下载失败: HTTP {response.status}"
                        )

                    total_size = int(response.headers.get('content-length', 0))
                    chunk_size = 8192
                    downloaded_size = 0

                    with open(destination, 'wb') as f:
                        async for chunk in response.content.iter_chunked(chunk_size):
                            f.write(chunk)
                            downloaded_size += len(chunk)
                            if progress_callback:
                                progress = (downloaded_size / total_size) * 100
                                progress_callback(progress)

                    return destination

        except asyncio.TimeoutError:
            raise NetworkError("下载超时")
        except Exception as e:
            raise NetworkError(f"下载失败: {str(e)}")